import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import router from '@/router'
import { constantRoutes, asyncRoutes } from '@/router/routes'
import { getNewRoutes, delNewRoutes, setNewRoutes } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    //刷新网页,vuex数据重新加载,
    newRoutes: getNewRoutes()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_NEWROUTERS: (state, data) => {
    state.newRoutes = data
  }
}

//计算该用户所拥有的路由
function computeAsyncRoutes(list, routes) {
  return list.filter((item) => {
    if (routes.indexOf(item.name) != -1) {
      // 子路由
      if (item.children && item.children.length) {
        item.children = computeAsyncRoutes(item.children, routes)
      }
      return true
    }
  })
}

const actions = {
  //登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const { data } = response
          // 保存toeken
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          if (response.code != 200 && response.code != 20000) {
            return reject('验证失败,请重新登录。')
          }
          const { name, avatar, routes } = response.data
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)

          // 菜单管理
          let newRoutes = computeAsyncRoutes(asyncRoutes, routes)
          let totalRoutes = constantRoutes.concat(newRoutes)
          commit('SET_NEWROUTERS', totalRoutes) // 保存仓库,更新侧边栏
          // router 添加路由
          // router.addRoutes(totalRoutes)

          setNewRoutes(totalRoutes) // 保存本地
          resetRouter() //重新设置路由
          resolve(response.data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          delNewRoutes() //删除路由
          resetRouter() //重新设置路由
          commit('RESET_STATE')
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
